<?php

namespace App\Admin\Actions\Admin;

use App\Models\AgentInfo;
use App\Models\AgentRechargeRecord;
use Encore\Admin\Actions\RowAction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class AgentRecharge extends RowAction
{
    protected $selector = '.agent-recharge';

    public $name = '充值';

    public function handle(AgentInfo $agentInfo,Request $request)
    {

        try {
            DB::beginTransaction();
            //记录日志
            AgentRechargeRecord::query()->create([
                'admin_user_id'=> $agentInfo->admin_user_id,
                'operator' => Auth::guard()->user()->name,
                'amount' => $request->amount,
                'balance' => $agentInfo->balance + $request->amount
            ]);
            $agentInfo->increment('balance',$request->amount);
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            return $this->response()->error('充值失败，请联系研发'.$exception->getMessage())->refresh();
        }

        return $this->response()->success('充值成功')->refresh();
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-default agent-recharge"></a>
HTML;
    }

    public function form()
    {
        $this->text('amount', '充值金额');
    }
}
